import React, { useState } from "react";
import { Form, Input, Button, Checkbox, message } from "antd";
import { UserOutlined, LockOutlined, GlobalOutlined } from "@ant-design/icons";
import "./index.scss";
import api from "../../api";
import { useHistory } from "react-router-dom";
const LoginForm = () => {
  const history = useHistory();
  const [isRegister, setIsRegister] = useState(false);
  const [registerData, setRegisterData] = useState({
    username: "",
    password: "",
    rePassword: "",
  });

  // 校验密码的函数
  const checkRePassword = (rule, value, callback) => {
    if (value === "") {
      callback(new Error("请再次确认密码"));
    } else if (value !== registerData.password) {
      callback(new Error("请确保两次输入的密码一样"));
    } else {
      callback();
    }
  };
  // 定义表单校验规则
  const rules = {
    username: [
      { required: true, message: "请输入用户名", trigger: "blur" },
      { min: 5, max: 16, message: "长度为5~16位非空字符", trigger: "blur" },
    ],
    password: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 5, max: 16, message: "长度为5~16位非空字符", trigger: "blur" },
    ],
    rePassword: [{ validator: checkRePassword, trigger: "blur" }],
  };

  const handleSwitchForm = () => {
    setIsRegister(!isRegister);
    clearRegisterData();
  };

  const clearRegisterData = () => {
    setRegisterData({
      username: "",
      password: "",
      rePassword: "",
    });
  };

  const onFinish = (values) => {
    if (isRegister) {
      api.register(values).then((res) => {
        if (res.success) {
          message.success("注册成功");
          setIsRegister(false);
         
        } else {
          message.error(res.message || "注册失败");
        }
      });
    } else {
      api
        .login({
          username: values.username,
          password: values.password,
        })
        .then((res) => {
          if (res.success) {
            message.success("登录成功");
            const { id ,username} = res.data;
            localStorage.setItem("userId", id);
            localStorage.setItem("username",username);
            history.push("/globalNews/home");
          } else {
            message.error(res.message || "登录失败");
          }
        });
    }
  };

  return (
    <div className="login-page">
      <div className="bg" style={{ flex: 1 }}></div>
      <div
        className="form"
        style={{
          flex: 1,
          display: "flex",
          flexDirection: "column",
          alignItems: "center",
        }}
      >
        <h1>{isRegister ? "注册" : "登录"}</h1>
        <Form
          name="loginForm"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          style={{ width: "100%", maxWidth: "400px" }}
        >
          <Form.Item name="username" rules={isRegister? rules.username : null}>
            <Input prefix={<UserOutlined />} placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="password" rules={isRegister? rules.password : null}>
            <Input.Password
              prefix={<LockOutlined />}
              onChange={(e) =>
                setRegisterData({ ...registerData, password: e.target.value })
              }
              placeholder="请输入密码"
            />
          </Form.Item>
          {isRegister && (
            <>
              <Form.Item name="rePassword" rules={rules.rePassword}>
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="请再次输入密码"
                />
              </Form.Item>

              <Form.Item
                name="companyName"
                rules={[{ required: true, message: "请输入公司名称" }]}
              >
                <Input
                  prefix={<GlobalOutlined />}
                  placeholder="请输入公司名称"
                />
              </Form.Item>
            </>
          )}
          {!isRegister && (
            <Form.Item name="remember">
              <div style={{ display: "flex", justifyContent: "space-between" }}>
                <Checkbox>记住我</Checkbox>
                {!isRegister && (
                  <span>
                    <a href="#">忘记密码？</a>
                  </span>
                )}
              </div>
            </Form.Item>
          )}
          <Form.Item>
            <Button type="primary" htmlType="submit" style={{ width: "100%" }}>
              {isRegister ? "注册" : "登录"}
            </Button>
          </Form.Item>
          <Form.Item>
            <span onClick={handleSwitchForm} style={{ cursor: "pointer" }}>
              {isRegister ? "← 返回" : "注册 →"}
            </span>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default LoginForm;
